# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '39333664': {  # <通道>:JUFPAY  <支付方式>:alipay wap 或 h5  <限额>：最低金额 1； 每小时限额 30000； 最大金额 5000；
        'API_KEY': 'a8dad26d0b8f1dc35a8b1ee3c37a02dd',
        'gateway': 'http://www.yifupaygate.com/channel/Common/mail_interface',
        'query_gateway': 'http://www.yifupaygate.com/channel/Common/query_pay',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("jufpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    params.pop('messages')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jufpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        payType = 'alipay'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('return_type', 'json'),
        ('api_code', app_id),
        ('is_type', _get_pay_type(service)),
        ('price', '%.2f' % pay_amount),
        ('order_id', str(pay.id)),
        ('time', int(time.time())),
        ('mark', 'charge'),
        ('return_url', '{}/pay/api/{}/jufpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notify_url', '{}/pay/api/{}/jufpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("jufpay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info('jufpay create rsp, %s', response.text)
    return {'charge_info': json.loads(response.text)['payurl']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("jufpay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('jufpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['paysapi_id']
    total_fee = float(data['real_price'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0 未处理 1 交易成功 2 支付失败 3 关闭交易 4 支付超时
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('jufpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('api_code', app_id),
        ('is_type', _get_pay_type(pay_order.service)),
        ('order_id', str(pay_order.id)),
        ('price', '%.2f' % float(pay_order.total_fee)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('jufpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info('jufpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        _LOGGER.info("jufpay query response body: %s", data)
        mch_id = pay_order.mch_id
        trade_status = str(data['code'])
        total_fee = float(data['price'])
        trade_no = data['paysapi_id']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('jufpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
